<script>
import COS from 'cos-js-sdk-v5'

export default {
  props: {
    staffPhoto: {
      type: String,
      default: ''
    }
  },
  methods: {
    // 上传前的检查
    beforeAvatarUpload(file) {
      const isImg = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImg) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF/BMP 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isImg && isLt5M
    },
    // 上传图片
    uploadImage(params) {
      // 上传到腾讯云oss
      const cos = new COS({
        SecretId: 'AKIDpkXfxAE5nKfokTzIn7JI4e1CAwWu53pP',
        SecretKey: 'QM7oJbicKpFUXO4Zt23ua3KpETXQAjBS'
      })
      cos.putObject({
        Bucket: 'huibaobao-1374618805',
        Region: 'ap-chongqing',
        Key: params.file.name,
        StorageClass: 'STANDARD',
        Body: params.file
      }, (err, data) => {
        if (data && data.statusCode === 200) {
          this.$emit('update:staffPhoto', 'http://' + data.Location)
        } else {
          this.$message.error(err.message)
        }
      })
    }
  }
}
</script>

<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
  >
    <img v-if="staffPhoto" :src="staffPhoto" class="avatar" alt="">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
